<template>
  <div class="example">
    Fade In: <input type="range" v-model="fadeInDuration" min="0" v-bind:max="maxFadeDuration">
    Fade Out: <input type="range" v-model="fadeOutDuration" min="0" v-bind:max="maxFadeDuration">
    <transition
      v-bind:css="false"
      v-on:before-enter="beforeEnter"
      v-on:enter="enter"
      v-on:leave="leave"
    >
      <p v-if="show">hello</p>
    </transition>
    <div class="btn">
      <button
        v-if="stop"
        v-on:click="stop = false; show = false"
      >Start animating</button>
      <button
        v-else
        v-on:click="stop = true"
      >Stop it!</button>
    </div>
  </div>
</template>

<script>
/**
 * 例子 - 动态过渡
 */

/**
 * 动态加载JavaScript
 */
function loadJS(url) {
  const script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = url;
  document.getElementsByTagName('head')[0].appendChild(script);
}

export default {
  data() {
    return {
      show: true,
      fadeInDuration: 1000,
      fadeOutDuration: 1000,
      maxFadeDuration: 1500,
      stop: true
    }
  },
  created() {
    loadJS('https://cdnjs.cloudflare.com/ajax/libs/velocity/1.2.3/velocity.min.js');
  },
  methods: {
    beforeEnter(el) {
      el.style.opacity = 0
    },
    enter(el, done) {
      var vm = this
      Velocity(el,
        { opacity: 1 },
        {
          duration: this.fadeInDuration,
          complete: function () {
            done()
            if (!vm.stop) vm.show = false
          }
        }
      )
    },
    leave(el, done) {
      var vm = this
      Velocity(el,
        { opacity: 0 },
        {
          duration: this.fadeOutDuration,
          complete: function () {
            done()
            vm.show = true
          }
        }
      )
    }
  }
}
</script>

<style lang="less" scoped>
.example {
  width: 600px;
}
</style>